import React, { PureComponent } from 'react';
import styles from './index.less';

class Drag extends PureComponent {
  constructor(...args) {
    super(...args);
    this.state = { x: 0, y: 0 };
  }

  fn(ev) {
    const disx = ev.pageX - this.state.x;
    const disy = ev.pageY - this.state.y;

    const _this = this;
    document.onmousemove = function (ev) {
      _this.setState({
        x: ev.pageX - disx,
        y: ev.pageY - disy,
      });
    };
    document.onmouseup = function () {
      document.onmousemove = null;
      document.onmousedown = null;
    };
  }

  render() {
    return (
      <div
        className={styles.box}
        style={{ transform: `translate(${this.state.x}px, ${this.state.y}px)` }}
        onMouseDown={this.fn.bind(this)}
      >
        {this.props.children}
      </div>
    );
  }
}
export default Drag;
